package com.chen.function_demo.chapter3;

import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

/**
 * 第三章第一节
 * @author 陈哲<p>
 * ================================<p>
 * Date: 2025/5/11<p>
 * Time: 23:17<p>
 * ================================
 */
public class Section1 {
    /*
        最基础的Stream API：
        1. filter：过滤
        2. map：映射
        3. flatMap：扁平化
     */
    // 定义一个水果类
    record Fruit(String name,  String category, String color, int price){}

    public static void main(String[] args) {
        // 创建一个集合
        List<Fruit> fruits = List.of(
                new Fruit("苹果", "fruit", "红色", 5),
                new Fruit("香蕉", "fruit", "黄色", 3),
                new Fruit("橘子", "fruit", "橘色", 2),
                new Fruit("梨", "fruit", "绿色", 4),
                new Fruit("葡萄", "fruit", "紫色", 6)
        );
        // 获取集合中所有水果价格大于3元的水果并打印
        fruits.stream()
                .filter(fruit -> fruit.price > 3) // filter(Predicate<? super T> predicate)
                .forEach(System.out::println);
        System.out.println("-----------------------------");
        // 获取集合中水果价格大于3元且颜色是红色的水果并打印
        fruits.stream()
                .filter(fruit -> fruit.price > 3 && fruit.color.equals("红色"))
                .forEach(System.out::println);
        System.out.println("-----------------------------");

        // 将集合中的水果变成果酱
        fruits.stream()
                .map(fruit -> fruit.name + "酱") // map(Function<? super T, ? extends R> mapper)
                .forEach(System.out::println);
        System.out.println("-----------------------------");

        // 创建两个集合
        List<Fruit> list1 = List.of(
                new Fruit("苹果", "水果", "红色", 5),
                new Fruit("香蕉", "水果", "黄色", 3),
                new Fruit("橘子", "水果", "橘色", 2),
                new Fruit("梨", "水果", "绿色", 4),
                new Fruit("葡萄", "水果", "紫色", 6)
        );
        List<Fruit> list2 = List.of(
                new Fruit("花生", "坚果", "黄色", 2),
                new Fruit("瓜子", "坚果", "黑色", 3),
                new Fruit("开心果", "坚果", "黄色", 5)
        );
        // 打印出来是两行数据,即Stream流中有两个元素，分别为list1和list2
        Stream.of(
                list1,
                list2
        ).forEach(System.out::println);
        System.out.println("-----------------------------");
        // 打印出来是多行数据，即Stream流中为多个元素（为list1和list2中的所有元素）
        Stream.of(
                        list1,
                        list2
                ).flatMap(Collection::stream)
                .forEach(System.out::println);
    }

}
